#include "material/shadowmaterial.h"


CShadowMaterial::CShadowMaterial() :
CMaterial() {
    strcpy( m_strName, "ShadowMaterial" );
}
CShadowMaterial::~CShadowMaterial() {

}
void CShadowMaterial::Init() {
    CMaterial::Init();

    const char* _strVertexShader = "\n\
/*#ifdef __HIGHTP__*/ \n\
    precision highp float; \n\
/*#endif*/ \n\
uniform mat4 projectionMatrix;\
uniform mat4 viewMatrix;\
uniform mat4 modelMatrix;\
uniform mat4 boneMatrices[250];\
attribute vec3 a_position;\
attribute vec2 a_texcoord0;\
attribute vec4 a_skinIndex;\
attribute vec4 a_skinWeight;\
varying vec2 vUv0;\
mat4 getBoneMatrix( const in float i ){\
    mat4 bone = boneMatrices[int( i )];\
    return bone;\
}\
void main(){\
mat4 boneMatX = getBoneMatrix( a_skinIndex.x ); \
mat4 boneMatY = getBoneMatrix( a_skinIndex.y ); \
mat4 boneMatZ = getBoneMatrix( a_skinIndex.z ); \
mat4 boneMatW = getBoneMatrix( a_skinIndex.w ); \
mat4 skinMatrix = mat4( 0.0 );\
skinMatrix += a_skinWeight.x * boneMatX;\
skinMatrix += a_skinWeight.y * boneMatY;\
skinMatrix += a_skinWeight.z * boneMatZ;\
skinMatrix += a_skinWeight.w * boneMatW;\
vec3 _vPosition = vec3( viewMatrix * skinMatrix * vec4( a_position, 1.0 ) );\
gl_Position = projectionMatrix * vec4( _vPosition, 1.0 );\
vUv0 = a_texcoord0;\
}";

    const char* _strFragmentShader = "\
/*#ifdef __HIGHTP__*/ \n\
    precision highp float; \n\
/*#endif*/ \n\
varying vec2 vUv0;\
uniform sampler2D diffuseMap;\
const float PackUpscale = 256. / 255.;\
const vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\
const float ShiftRight8 = 1. / 256.;\
vec4 LinearToLinear( in vec4 value ){\n\
    return value;\n\
}\n\
vec4 mapTexelToLinear( vec4 value ){ return LinearToLinear( value ); }\n\
vec4 packDepthToRGBA( const in float v ){\
    vec4 r = vec4( fract( v * PackFactors ), v );\
    r.yzw -= r.xyz * ShiftRight8;\
    return r * PackUpscale;\
}\
void main(){\
    vec4 diffuseColor = vec4( 1.0 );\
	vec4 texelColor = texture2D( diffuseMap, vUv0 ); \
    texelColor = mapTexelToLinear( texelColor );\
    diffuseColor *= texelColor;\
    if ( diffuseColor.a < 0.1 ) discard;\
    gl_FragColor = packDepthToRGBA( gl_FragCoord.z );\
}\
";

    m_hMaterialHandle = Material_Create(m_strName, (byte*)_strVertexShader, strlen(_strVertexShader), (byte*)_strFragmentShader, strlen(_strFragmentShader));
    m_hProjectionMatrixHandle = Material_GetUniform(m_hMaterialHandle, "projectionMatrix", EUT_MATRIX44);
    m_hViewMatrixHandle = Material_GetUniform( m_hMaterialHandle, "viewMatrix", EUT_MATRIX44 );
    m_hModelMatrixHandle = Material_GetUniform( m_hMaterialHandle, "modelMatrix", EUT_MATRIX44 );
    m_hBoneMatricesHandle = Material_GetUniform(m_hMaterialHandle, "boneMatrices", EUT_MATRIX44 );
    m_hDiffuseMapHandle = Material_GetUniform(m_hMaterialHandle, "diffuseMap", EUT_SAMPLER);
}

